package cn.itcast.springboot.config;

import cn.itcast.springboot.security.MyUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @description:
 * @author: YHL
 * @time: 2021/1/7 10:01 下午
 */
@Configuration
public class MyWebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    MyUserDetailService myUserDetailService;

    @Override
    public void configure(WebSecurity web) throws Exception {
//        通用 静态 资源 放行 不经过过滤器链 处理
        web.ignoring().antMatchers("/css/**", "/js/**", "/img**");
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
//        重写  认证 账号 密码以及权限或者角色信息
        String  password =creat().encode("123");
        auth.inMemoryAuthentication().passwordEncoder(creat()).withUser("yhl").password(password).roles("admin")
                .and()
                .withUser("tom").password(password).roles("query");
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.formLogin()//配置表单数据
                .loginPage("/login.html")
                .loginProcessingUrl("/login")
                .defaultSuccessUrl("/user1.html")
                .failureUrl("/login.html")
                .and()
                .authorizeRequests().antMatchers("/user1.html","/user-e.html").authenticated()
                .antMatchers("/user/**").hasRole("admin")
                .and()
                .exceptionHandling().accessDeniedPage("/error.html")
                .and()
                .csrf().disable();//禁用CsrfFilter
    }

    @Bean
    public PasswordEncoder creat(){
        return new BCryptPasswordEncoder();
    }
}


